#pragma once
#include <iostream>
#include <queue>
#include <pthread.h>
#include "SmartMutex.hpp"
using namespace std;

const int default_capvalue = 5;

template <class T>
class BLQueue
{
public:
    BLQueue(size_t cap = default_capvalue)
        : _capacity(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);

        pthread_cond_init(&_c_cond, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
    }

    bool IsFull()
    {
        return _q.size() == _capacity;
    }

    bool IsEmpty()
    {
        return _q.size() == 0;
    }

    void Push(const T &in) // 生产者生产数据
    {
        // pthread_mutex_lock(&_mutex);
        SmartMutex smartmutex(&_mutex);

        // if(_q.size() == _capacity)
        while (IsFull())
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }

        _q.push(in);
        pthread_cond_signal(&_c_cond);
        // pthread_mutex_unlock(&_mutex);
    }

    void Pop(T *out) // 消费者消费数据
    {

        // pthread_mutex_lock(&_mutex);
        SmartMutex smartmutex(&_mutex);

        // if(_q.size() == 0)
        while (IsEmpty())
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }

        *out = _q.front();
        _q.pop();
        pthread_cond_signal(&_p_cond);
        // pthread_mutex_unlock(&_mutex);
    }

    ~BLQueue()
    {
        pthread_mutex_destroy(&_mutex);

        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

private:
    queue<T> _q;
    size_t _capacity;
    pthread_mutex_t _mutex;

    pthread_cond_t _c_cond; // 消费者的
    pthread_cond_t _p_cond; // 生产者的
};